package com.adonis.ejoy.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.adonis.ejoy.Item.Follow;
import com.adonis.ejoy.Item.MyPic;
import com.adonis.ejoy.R;
import com.adonis.ejoy.adapter.MyPicAdapter;
import com.adonis.ejoy.bean.User;
import com.adonis.ejoy.utils.HttpUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yanzhenjie.album.Album;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static android.app.Activity.RESULT_OK;


public class MeFragment extends Fragment {

    private String baseURL;
    private int uid;
    private View view;
    private List<MyPic> myPicList=new ArrayList<>();
    private User user=new User();
    private static final int OPEN_ALBUM=2;               //版本
    private int chooseable=1;                               //可选择的数量
    private List<String> photoList = new ArrayList<>();

    @BindView(R.id.userfind_btn)
    ImageButton userfindbtn;
    @BindView(R.id.more_btn)
    ImageButton morebtn;
    @BindView(R.id.myname)
    TextView myName;
    @BindView(R.id.user_icon)
    ImageButton usericon;
    @BindView(R.id.posts_num)
    TextView postsNum;
    @BindView(R.id.followers_num)
    TextView followersNum;
    @BindView(R.id.followings_num)
    TextView followingsNum;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view=inflater.inflate(R.layout.fragment_me, container, false);
        ButterKnife.bind(this,view);

        baseURL = view.getContext().getString(R.string.baseURL);
        uid = ((TextView)getActivity().findViewById(R.id.user_info)).getMaxWidth();
        getUserInfo();                                       //得到用户信息
        return view;
    }

    private void initView() {
        //设置登录用户的名字
        myName.setText(user.getName());
        postsNum.setText(user.getPosts()+"");
        followersNum.setText(user.getFans()+"");
        followingsNum.setText(user.getFollows()+"");

        initPopPic();       //以下为MeFragment下的瀑布流的实现
        RecyclerView recyclerViewMP = (RecyclerView) view.findViewById(R.id.MP_waterfall);
        StaggeredGridLayoutManager layoutManagerSG = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL){
            @Override
            public boolean canScrollVertically() {
                return false;
            }  //消除互动歧义，可以快速顺畅的滑动
        };
        recyclerViewMP.setLayoutManager(layoutManagerSG);
        MyPicAdapter myPicAdapter = new MyPicAdapter(myPicList);
        recyclerViewMP.setAdapter(myPicAdapter);
    }

    @OnClick({R.id.user_icon,R.id.more_btn,R.id.userfind_btn})
    public void onClick(View v){
        switch (v.getId()){
            case R.id.userfind_btn:
                Toast.makeText(view.getContext(), "正在实现",Toast.LENGTH_SHORT).show();
                break;
            case R.id.more_btn:
                Toast.makeText(view.getContext(), "正在实现",Toast.LENGTH_SHORT).show();
                break;
            //设置头像
            case R.id.user_icon:
                Album.startAlbum(this, OPEN_ALBUM,chooseable);
                break;
        }
    }

    private void initPopPic() {
        //此功能获取用户自己发表的所有照片此处循环3次处理
        for (int i = 0; i < 3; i++) {
            MyPic myPic1 = new MyPic(R.drawable.mypic1);
            myPicList.add(myPic1);
            MyPic myPic2 = new MyPic(R.drawable.mypic2);
            myPicList.add(myPic2);
            MyPic myPic3 = new MyPic(R.drawable.mypic3);
            myPicList.add(myPic3);
            MyPic myPic4 = new MyPic(R.drawable.mypic4);
            myPicList.add(myPic4);
            MyPic myPic5 = new MyPic(R.drawable.mypic5);
            myPicList.add(myPic5);
            MyPic myPic6 = new MyPic(R.drawable.mypic6);
            myPicList.add(myPic6);
            MyPic myPic7 = new MyPic(R.drawable.mypic7);
            myPicList.add(myPic7);
            MyPic myPic8 = new MyPic(R.drawable.mypic8);
            myPicList.add(myPic8);
            MyPic myPic9 = new MyPic(R.drawable.mypic9);
            myPicList.add(myPic9);
        }
    }

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.obj instanceof User){
                user = (User) msg.obj;
                initView();
            }
        }
    };

    private void getUserInfo() {
        //获取用户的个人信息
        final String url = baseURL + "mvc/login?&uid="+uid;
        HttpUtil.sendGetRequest(url,new Callback() {             //发送网络请求不能在主线程中进行
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("onFailure: ", "failed");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call,final Response response) throws IOException {
                String jsonData = response.body().string();
                Gson gson = new Gson();
                User user = gson.fromJson(jsonData,User.class);  //将JSON数组解析为Post集合
                Message message = new Message();
                message.obj = user;
                handler.sendMessage(message);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case OPEN_ALBUM:
                if(resultCode==RESULT_OK){
                    List<String> pathList = Album.parseResult(data);
                    displayImage(pathList);
                }
                break;
            default: break;
        }
    }

    private void displayImage(List<String> pathList) {
        photoList.addAll(pathList);
        for (String imagepath:pathList) {
            if(imagepath!=null){
                Bitmap bitmap= BitmapFactory.decodeFile(imagepath);
                usericon.setImageBitmap(bitmap);
            }else{
                Toast.makeText(this.getContext(), "failed to get image", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
